package com.zhou.simulation.service.impl;

import com.sun.mail.util.MailSSLSocketFactory;
import com.zhou.simulation.beans.MailInfoBean;
import com.zhou.simulation.service.MailSendService;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * @ProjectName: simulation
 * @Package: com.zhou.simulation.service.impl
 * @ClassName: MailSendServiceImpl
 * @Author: zhoujingbo
 * @Description: <p>
 * @Date: 2020/10/10 15:31
 * @Version: 1.0
 */
@Service
public class MailSendServiceImpl implements MailSendService {
    private static final String TOKEN = "xrzjgtmwrrcqbaeg";
    @Override
    public boolean doMailSend(MailInfoBean mailInfoBean){
        System.out.println(mailInfoBean);
        Transport transport = null;
        try {
            //创建一个配置文件并保存
            Properties properties = new Properties();

            properties.setProperty("mail.host","smtp.qq.com");

            properties.setProperty("mail.transport.protocol","smtp");

            properties.setProperty("mail.smtp.auth","true");

            //QQ存在一个特性设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            //创建一个session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("1377072049@qq.com",TOKEN);
                }
            });
            //开启debug模式
            session.setDebug(true);

            //获取连接对象
            transport = session.getTransport();

            //连接服务器
            transport.connect("smtp.qq.com","1377072049@qq.com",TOKEN);
            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);

            //邮件发送人
            mimeMessage.setFrom(new InternetAddress("1377072049@qq.com"));

            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(mailInfoBean.getRecipient()));

            //邮件标题
            mimeMessage.setSubject("Hello HeYu");

            //邮件内容
            mimeMessage.setContent("我的想法是把代码放进一个循环里","text/html;charset=UTF-8");

            //发送邮件
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
